package net.alteiar.algorithms;

import java.awt.Color;
import java.awt.image.BufferedImage;

import net.alteiar.images.BasicImage;
import net.alteiar.images.metadata.ImageInfo;

public class ImageInfoUtils {

	private static Color doAverage(BasicImage img, int x, int y, int squareSize) {
		int r = 0;
		int g = 0;
		int b = 0;
		BufferedImage im = img.getImage();

		int realX = x * squareSize;
		int realY = y * squareSize;
		for (int k = 0; k < squareSize; ++k) {
			for (int k1 = 0; k1 < squareSize; ++k1) {
				Color c = new Color(im.getRGB(realX + k, realY + k1));
				r += c.getRed();
				g += c.getGreen();
				b += c.getBlue();
			}
		}

		int nbSquare = squareSize * squareSize;

		return new Color(r / nbSquare, g / nbSquare, b / nbSquare);
	}

	public static ImageInfo buildAverage(BasicImage img, int squareSize) {
		ImageInfo info = new ImageInfo(img, squareSize);

		for (int x = 0; x < info.getWidthSquare(); x++) {
			for (int y = 0; y < info.getHeightSquare(); y++) {
				Color c = doAverage(img, x, y, squareSize);
				info.setValue(x, y, c.getRGB());
			}
		}
		return info;
	}

}
